package com.sxm.yiwei.activitis;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.InternetAddressUtis;
import com.sxm.yiwei.views.ValidationCode;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

public class ForgetPassWordActivity extends BaseActivity implements View.OnClickListener{

    private ImageView forgetback;
    private ImageView phoneclear;
    private EditText inphone;
    private EditText inphonecode;
    private EditText inpiccode;
    private Button surebt;
    private ValidationCode piccode;
    private Button getcode;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private String phone;
    private String data;
    private String messageId;
    private ImageView backmain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_pass_word);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid", "0");
        userId = sharedPreferences.getString("uesrId", "1");
        token = sharedPreferences.getString("token", "2");

        initForgetView();

    }

    private void initForgetView() {
        forgetback = (ImageView) findViewById(R.id.forget_wordback);
        phoneclear = (ImageView) findViewById(R.id.forget_phoneclear);
        inphone = (EditText) findViewById(R.id.forget_inphone);
        inpiccode = (EditText) findViewById(R.id.forget_inpiccode);
        inphonecode = (EditText) findViewById(R.id.forget_inphonecode);
        surebt = (Button) findViewById(R.id.forget_surebt);
        piccode = (ValidationCode) findViewById(R.id.forget_piccode);
        getcode = (Button) findViewById(R.id.forget_getcode);
        backmain = (ImageView) findViewById(R.id.forgetpassword_backmain);
        backmain.setOnClickListener(this);
        forgetback.setOnClickListener(this);
        phoneclear.setOnClickListener(this);
        getcode.setOnClickListener(this);
        surebt.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.forgetpassword_backmain:
                startActivity(new Intent(ForgetPassWordActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();

                break;
            case R.id.forget_wordback:
                finish();
                break;
            case R.id.forget_phoneclear:
                inphone.setText("");
                break;
            case R.id.forget_surebt:
                String phonecode = String.valueOf(inphonecode.getText());
                if (!phonecode.equals("")&&phonecode.length()==6){
                    Intent intent = new Intent(ForgetPassWordActivity.this,ForgetInWordActivity.class);
                    intent.putExtra("code",phonecode);
                    intent.putExtra("phone",phone);
                    intent.putExtra("messageId",messageId);
                    startActivity(intent);
                    finish();
                }else {
                    Toast.makeText(this, "请输入正确的手机验证码", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.forget_getcode:
                phone = String.valueOf(inphone.getText());
                String codeString = piccode.getCodeString();
                String incode = String.valueOf(inpiccode.getText());

                if (isPhoneNumber(phone)){
                    if (!incode.equals("")){
                        Toast.makeText(this, "验证码获取中", Toast.LENGTH_SHORT).show();
                        MyTimer timer = new MyTimer(120000,1000);
                        timer.start();
                        getCode();
                    }else {
                        Toast.makeText(this, "请输入图形验证码", Toast.LENGTH_SHORT).show();
                    }

                }else {
                    Toast.makeText(this, "手机号码格式错误", Toast.LENGTH_SHORT).show();
                }
                break;

        }
    }

    // 验证手机号
    private boolean isPhoneNumber(String phone) {
        String isPhone = "[1][34578]\\d{9}";
        boolean matches = phone.matches(isPhone);

        return matches;

    }

    // 获取验证码
    public void getCode() {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/verify/sendCodeNotLogin");
        params.addHeader("Content-Type","application/json");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type","4");
        jsonObject.put("mobile",phone);
        params.addParameter("params",jsonObject.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("tag", "onSuccess: 修改密码--"+result);
                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
                // 获取messageid
                data = obj.getString("data");
                com.alibaba.fastjson.JSONObject obj1 = JSON.parseObject(data);
                messageId = obj1.getString("messageId");


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onError: 修改--"+ex);
                ErrType.errType(ForgetPassWordActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    class MyTimer extends CountDownTimer {
        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                  倒计时数        to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *           倒计时间隔               {@link #onTick(long)} callbacks.
         */
        public MyTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            getcode.setClickable(false);
            getcode.setText(millisUntilFinished/1000+"s");
        }

        @Override
        public void onFinish() {
            getcode.setClickable(true);
            getcode.setText("验证码");
        }
    }


}
